package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.entity.LoginUser;
import com.example.demo.entity.User;
import com.example.demo.mapper.MenuMapper;
import com.example.demo.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Description : 重载UserDetailsServiceImpl，实现从数据库中查询数据
 * @Author : Bruce Lee
 * @CreateTime : 2023/11/28
 */

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUserName, s);

        User loginUser = userMapper.selectOne(userLambdaQueryWrapper);
        if (Objects.isNull(loginUser)) {
            log.info("用户名或密码错误");
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        // 去数据库中查询该用户权限
        List<String> permissions = menuMapper.selectMenuById(loginUser.getId());
        return new LoginUser(loginUser, permissions);

    }

}
